﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TLang.Ast
{
    using Values;

    public class If : Node
    {
        public Node test;
        public Node then;
        public Node orelse;


        public If(Node test, Node then, Node orelse, String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this.test = test;
            this.then = then;
            this.orelse = orelse;
        }


        public override Value Interp(Scope s)
        {
            Value tv = Interp(test, s);
            if (((BoolValue)tv).Value)
            {
                return Interp(then, s);
            }
            else
            {
                return Interp(orelse, s);
            }
        }

        public override Value Typecheck(Scope s)
        {
            Value tv = Typecheck(test, s);
            if (!(tv is BoolType))
            {
                Util.Abort(test, "test is not boolean: " + tv);
                return null;
            }
            Value type1 = Typecheck(then, s);
            Value type2 = Typecheck(orelse, s);
            return UnionType.union(type1, type2);
        }


        public override String ToString()
        {
            return "(" + Constants.IF_KEYWORD + " " + test + " " + then + " " + orelse + ")";
        }
    }
}
